<template>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>考试申请导入</span>
      </div>
  
      <el-row :gutter="20" justify="center" style="margin-bottom: 20px;">
        <el-col :span="24" style="text-align: center;">
          <el-button type="primary" icon="el-icon-download" @click="downloadTemplate">
            下载导入模板
          </el-button>
          <p style="margin-top: 8px; color: #888;">请先下载模板并填写完整后再上传</p>
        </el-col>
      </el-row>
  
      <el-divider content-position="center">上传Excel文件</el-divider>
  
      <el-row justify="center">
        <el-col :span="24" style="text-align: center;">
         
          <el-button type="primary" @click="chooseFile">上传导入</el-button>
            <input ref="upFile" class="file" name="file" type="file" style="display: none" @change="doImport">
        </el-col>
     
      </el-row>
    </el-card>
  </template>
  
  <script>
  import { templateApply ,importExcelApply} from '@/api/qu/qu';
  
  export default {
    data() {
      return {
        importUrl: '/api/exam/apply/import',
        fileList: [],
        importResult: '',
      };
    },
    methods: {
        doImport(e) {
      const file = e.target.files[0]

      importExcelApply(file).then(res => {
        if (res.code !== 0) {
          this.$alert(res.data.msg, '导入信息', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$message({
            message: '数据导入成功！',
            type: 'success'
          })
          this.fileList=[]
   
        }
      })
    },
          // 只是为了美化一下导入按钮
    chooseFile: function() {
      this.$refs.upFile.dispatchEvent(new MouseEvent('click'))
    },

      downloadTemplate() {
       
        templateApply();
      },
      beforeUpload(file) {
        const isExcel =
          file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.type === 'application/vnd.ms-excel';
        if (!isExcel) {
          this.$message.error('只能上传 Excel 文件');
          return false;
        }
        this.fileList = [file]; // 限制只保留一个文件
        return true;
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      handleSuccess(response) {
        if (response.success) {
          this.importResult = '导入成功！';
        } else {
          this.importResult = '导入失败: ' + (response.message || '未知错误');
        }
      },
      handleError() {
        this.importResult = '导入出错，请重试';
      },
    },
  };
  </script>
  
  <style scoped>
  .upload-demo {
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    background-color: #fafafa;
    padding: 20px;
    text-align: center;
  }
  </style>
  